package com.hzgj.bcl.soa.cicada.pool;

import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

import java.util.Collection;
import java.util.Map;

import io.netty.channel.pool.ChannelPool;

/**
 * Created by warning5 on 2017/3/6.
 */
public class ChannelPoolManager {

    public static final String DEFAULT_POOL_KEY = "default.pool.key";
    private Map<String, ChannelPool> pools = Maps.newHashMap();

    public void addChannelPool(String key, ChannelPool channelpool) {
        pools.putIfAbsent(key, channelpool);
    }

    public ChannelPool getChannelPool(String key) {
        ChannelPool channelPool = pools.get(key);
        if (channelPool == null) {
            channelPool = pools.get(DEFAULT_POOL_KEY);
            if (channelPool == null) {
                throw new RuntimeException("can't get channelPool by default key.");
            } else {
                pools.put(key, channelPool);
            }
        }
        return channelPool;
    }

    public Collection<ChannelPool> getPools() {
        return Sets.newHashSet(pools.values());
    }

    public void stop() {
        pools.values().forEach(ChannelPool::close);
        pools.clear();
    }
}
